package jianzhiOffer;
//剑指 Offer 67. 把字符串转换成整数
public class Num67_strToInt {
    public int strToInt(String str) {

        char[]arr = str.trim().toCharArray();//删除首位空格，转为字符数组
        if(arr.length == 0)return 0;
        int sign = 1;
        if (arr[0] == '+'){
            arr[0] = '0';
            sign = 1;
        }else if (arr[0] == '-'){
            arr[0] = '0';
            sign = -1;
        }else if (!(arr[0] >= '0' && arr[0] <= '9' )){
            return 0;
        }
        long sum = 0;
        for (int i = 0; i < arr.length; i++) {
            char ch = arr[i];
            if (Character.isDigit(ch)){
                sum = sum * 10 + (ch - '0');
            }else {
                break;
            }
            if (sum > Integer.MAX_VALUE){
                if (sign == 1)return Integer.MAX_VALUE;
                else return Integer.MIN_VALUE;
            }
        }
        return (int)sum * sign;
    }
}
